<?php
/**
 * Created by PhpStorm.
 * User: jochen
 * Date: 2017/1/6
 * Time: 下午3:52
 */

namespace EWeiLink\JuPai;
use DB;
use Jenssegers\Mongodb\Eloquent\Model;
use MongoDB\BSON\Regex;

/**
 * 微信联系人信息，用于保存来源于微信的联系人信息和系统中的关联关系。
 * Class Contact
 * @package EWeiLink\JuPai
 * @property string $_id             联系人ID
 * @property int $customerId      钜派客户ID， 如果为空则是未绑定状态。
 * @property string $clientUin       微信号UIN
 * @property string $ewlink_id       易微链系统ID
 * @property string $plannerId       所属理财师
 * @property-read \stdClass $wechatInfo  联系人的微信信息
 * @method static Contact|null find($id)
 */
class Contact extends Model
{
    protected $connection = JuPai::plugin_database_name;
    protected $guarded = [];
    protected $hidden = ['ewlinkInfo', '_class'];
    protected $appends = ['wechatInfo', 'jpInfo'];
    protected $_wechatInfo = null;
    protected $_jpInfo = null;
    protected $wechatInfoFields = ['nickName', 'headImg', 'account', 'province', 'city'];

    /**
     * 获取对应的理财师
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function planner()
    {
        return $this->hasOne(Planner::class, 'plannerId', 'plannerId');
    }

    /**
     * 获取易微链系统中的客户信息
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function ewlinkInfo()
    {
        return $this->hasOne(Customer::class, '_id', 'ewlink_id');
    }

    /**
     * 获取联系人来自微信的常规信息
     * @return \stdClass
     */
    public function getWechatInfoAttribute()
    {
        if (is_null($this->_wechatInfo)) {
            $this->getWechatInfo();
        }
        return $this->_wechatInfo;
    }

    public function getJpInfoAttribute() {
        if (is_null($this->_jpInfo)) {
            $this->getJpInfo();
        }
        return $this->_jpInfo;
    }

//    public function jpInfo()
//    {
//        return $this->hasOne(JpCustomer::class, 'customerId', 'customerId');
//    }

    public function scopeFindByBindState($query, $bindState)
    {
        if($bindState === null) return $query;
        if ($bindState === 0) {
            return $query->where('customerId', 0);
        } else {
            return $query->where('customerId', '>', 0);
        }
    }

    public function scopeFindByAccount($query, $account, $boolean='and')
    {
        if ($account) {
            $findIds = Customer::where('socialInfo.wechat.account', $account)->pluck('_id');
            if (empty($findIds)) return $query;
            return $boolean === 'and' ? $query->whereIn('ewlink_id', $findIds) : $query->orWhereIn('ewlink_id', $findIds);;
        }
        return $query;
    }

    public function scopeFindByPlannerId($query, $plannerId)
    {
        if($plannerId === null) return $query;
        return $query->where('plannerId', $plannerId);
    }

    public function scopeFindByJpName($query, $jpName, $boolean='and')
    {
        if(empty($jpName)) return $query;
        $findIds = JpCustomer::where('name', new Regex($jpName, 'ig'))->pluck('customerId');
        if (empty($findIds)) return $query;
        return $boolean === 'and' ? $query->whereIn('customerId', $findIds) : $query->orWhereIn('customerId', $findIds);
    }

    public function scopeFindByNickName($query, $nickName, $boolean='and') {
        if(empty($nickName)) return $query;
        $findIds = Customer::where('socialInfo.wechat.nickName', new Regex($nickName, 'gi'))->pluck('_id');
        if (empty($findIds)) return $query;
        return $boolean === 'and' ? $query->whereIn('ewlink_id', $findIds) : $query->orWhereIn('ewlink_id', $findIds);
    }

    public function scopeEwlinkId($query, $id)
    {
        if ($id) {
            return $query->where('ewlink_id', $id);
        }
        return $query;
    }

    public function scopeClientUin($query, $clientUin)
    {
        if ($clientUin) {
            return $query->where('clientUin', intval($clientUin));
        }

        return $query;
    }

    /**
     * 从对应的易微链客户信息中提取微信信息
     */
    protected function getWechatInfo()
    {
        $customer = $this->ewlinkInfo;
        if (isset($customer->socialInfo) && isset($customer->socialInfo['wechat'])) {
            $rawInfo = $customer->socialInfo['wechat'];
            $wechatInfo = new \stdClass();
            array_walk($this->wechatInfoFields, function ($field) use ($wechatInfo, $rawInfo) {
                $wechatInfo->$field = array_get($rawInfo, $field, '');
            });
            $this->_wechatInfo = $wechatInfo;
        }
    }

    protected function getJpInfo()
    {
        if ($this->customerId > 0) {
            $this->_jpInfo = JpCustomer::where('customerId', $this->customerId)->first();
        }
    }
}
